extends Area2D

# 剑气波的基本属性
var speed = 400  # 移动速度
var damage = 15  # 基础伤害
var direction = Vector2.RIGHT  # 移动方向
var lifetime = 1.0  # 存在时间
var has_hit = []  # 已经击中的敌人列表，防止多次伤害

# 视觉效果
var wave_color = Color(0.2, 0.5, 1.0, 0.7)  # 蓝色半透明
var wave_width = 70  # 增加长度，更像剑气
var wave_height = 16  # 减小高度，更具锋利感

func _ready():
	# 设置碰撞检测
	body_entered.connect(_on_body_entered)
	
	# 创建定时器，控制剑气波的生命周期
	var timer = Timer.new()
	timer.wait_time = lifetime
	timer.one_shot = true
	timer.timeout.connect(_on_lifetime_timeout)
	add_child(timer)
	timer.start()
	
	# 创建视觉效果
	create_visual_effect()
	
	# 播放音效
	play_sound_effect()
	
	# 确保碰撞层和掩码设置正确
	set_collision_layer_value(4, true)  # 设置为第4层
	set_collision_mask_value(2, true)   # 设置碰撞掩码为第2层，检测敌人
	
	# 确保碰撞形状存在且激活
	var collision_shapes = []
	for child in get_children():
		if child is CollisionShape2D:
			collision_shapes.append(child)
			child.disabled = false
			print("找到碰撞形状：", child.name, "，已启用")
	
	if collision_shapes.size() == 0:
		print("警告：剑气波没有碰撞形状！创建一个更长更窄的碰撞形状")
		var collision = CollisionShape2D.new()
		var shape = RectangleShape2D.new()
		# 修改碰撞形状，使其更细长
		shape.size = Vector2(wave_width * 1.2, wave_height * 0.6)
		collision.shape = shape
		add_child(collision)
	
	print("剑气波初始化完成，位置：", global_position, "，碰撞层：", get_collision_layer(), "，碰撞掩码：", get_collision_mask())
	
	# 打印场景中所有敌人
	print("场景中的敌人：")
	var enemies = get_tree().get_nodes_in_group("enemy")
	for enemy in enemies:
		print(" - ", enemy.name, "，位置：", enemy.global_position, "，距离：", global_position.distance_to(enemy.global_position))

func _process(delta):
	# 移动剑气波
	position += direction * speed * delta
	
	# 添加一些视觉效果，如轻微的上下浮动
	position.y += sin(Time.get_ticks_msec() * 0.01) * 0.2
	
	# 主动检测敌人并造成伤害
	check_for_enemies()
	
	# 更新剑气后面的拖尾特效
	update_trail_effect()

# 更新剑气的拖尾特效
func update_trail_effect():
	var trail_node = get_node_or_null("SwordTrail")
	if trail_node and trail_node is Line2D:
		# 在拖尾开头添加一个新的点
		var new_point = Vector2(-direction.x * 5, 0)  # 根据方向添加偏移
		trail_node.add_point(new_point)
		
		# 限制拖尾点的数量
		if trail_node.get_point_count() > 15:
			trail_node.remove_point(0)
		
		# 更新拖尾颜色渐变
		var new_gradient = Gradient.new()
		new_gradient.add_point(0.0, Color(0.3, 0.7, 1.0, 0.0))  # 尾部（较老的点）透明
		new_gradient.add_point(1.0, Color(0.3, 0.7, 1.0, 0.4))  # 头部（较新的点）不透明
		trail_node.gradient = new_gradient

# 主动检测敌人并造成伤害
func check_for_enemies():
	# 获取所有敌人
	var enemies = get_tree().get_nodes_in_group("enemy")
	if enemies.size() > 0:
		print("检测到", enemies.size(), "个敌人")
		for enemy in enemies:
			# 计算距离
			var distance = global_position.distance_to(enemy.global_position)
			print("敌人：", enemy.name, "，距离：", distance, "，已击中：", enemy in has_hit)
			
			# 增加检测范围从50到80
			if distance < 80 and not enemy in has_hit:  # 如果敌人在范围内且未被击中
				print("主动检测到敌人：", enemy.name, "，距离：", distance)
				# 添加到已击中列表
				has_hit.append(enemy)
				
				# 对敌人造成伤害
				if enemy.has_method("take_damage"):
					print("剑气波击中敌人：", enemy.name, "，造成伤害：", damage)
					# 检查take_damage函数需要的参数数量
					var method_list = enemy.get_method_list()
					var take_damage_method = null
					for method in method_list:
						if method.name == "take_damage":
							take_damage_method = method
							break
					
					if take_damage_method:
						print("take_damage方法参数数量：", take_damage_method.args.size())
						if take_damage_method.args.size() == 1:
							enemy.take_damage(damage)  # 只传递伤害值
						else:
							enemy.take_damage(damage, global_position)  # 传递伤害值和位置
					else:
						print("警告：无法获取take_damage方法信息，尝试使用两个参数调用")
						enemy.take_damage(damage, global_position)  # 传递伤害值和位置
					
					# 添加击中效果
					create_hit_effect(enemy.global_position)

func _on_body_entered(body):
	print("剑气波检测到碰撞：", body.name, "，组：", body.get_groups())
	
	# 检查是否是敌人
	if body.is_in_group("enemy") and not body in has_hit:
		# 添加到已击中列表
		has_hit.append(body)
		
		# 对敌人造成伤害
		if body.has_method("take_damage"):
			print("剑气波击中敌人：", body.name, "，造成伤害：", damage)
			# 检查take_damage函数需要的参数数量
			var method_list = body.get_method_list()
			var take_damage_method = null
			for method in method_list:
				if method.name == "take_damage":
					take_damage_method = method
					break
			
			if take_damage_method:
				print("take_damage方法参数数量：", take_damage_method.args.size())
				if take_damage_method.args.size() == 1:
					body.take_damage(damage)  # 只传递伤害值
				else:
					body.take_damage(damage, global_position)  # 传递伤害值和位置
			else:
				print("警告：无法获取take_damage方法信息，尝试使用两个参数调用")
				body.take_damage(damage, global_position)  # 传递伤害值和位置
			
			# 添加击中效果
			create_hit_effect(body.global_position)

func _on_lifetime_timeout():
	# 创建消失效果
	create_disappear_effect()
	
	# 停止所有粒子发射
	for child in get_children():
		if child is CPUParticles2D:
			child.emitting = false
	
	# 开始淡出所有视觉效果
	var tween = create_tween()
	for child in get_children():
		if child is CanvasItem and child.visible:
			tween.parallel().tween_property(child, "modulate", Color(child.modulate.r, child.modulate.g, child.modulate.b, 0), 0.2)
	
	# 延迟一小段时间后销毁，让效果有时间播放
	await get_tree().create_timer(0.2).timeout
	queue_free()

func create_visual_effect():
	# 创建剑气波的主体形状 - 改为多边形，更像剑气
	var wave_shape = Polygon2D.new()
	wave_shape.name = "SwordWaveShape"
	
	# 决定多边形顶点位置 - 根据方向调整形状
	var point_right = direction.x >= 0
	var points = []
	
	if point_right:
		# 向右的剑气波形状 - 更加细长锋利
		points.append(Vector2(-wave_width/2, -wave_height/4))     # 左上
		points.append(Vector2(-wave_width/3, -wave_height/2))     # 左上凸起
		points.append(Vector2(wave_width/4, -wave_height/6))      # 中上
		points.append(Vector2(wave_width/2, 0))                  # 最右尖端
		points.append(Vector2(wave_width/4, wave_height/6))       # 中下
		points.append(Vector2(-wave_width/3, wave_height/2))      # 左下凸起
		points.append(Vector2(-wave_width/2, wave_height/4))      # 左下
	else:
		# 向左的剑气波形状 - 对称版本
		points.append(Vector2(wave_width/2, -wave_height/4))      # 右上
		points.append(Vector2(wave_width/3, -wave_height/2))      # 右上凸起
		points.append(Vector2(-wave_width/4, -wave_height/6))     # 中上
		points.append(Vector2(-wave_width/2, 0))                 # 最左尖端
		points.append(Vector2(-wave_width/4, wave_height/6))      # 中下
		points.append(Vector2(wave_width/3, wave_height/2))       # 右下凸起
		points.append(Vector2(wave_width/2, wave_height/4))       # 右下

	wave_shape.polygon = points
	wave_shape.color = Color(0.4, 0.7, 1.0, 0.2)  # 设为半透明
	add_child(wave_shape)
	
	# 使用渐变色，给剑气一个更锋利的视觉效果
	var gradient = Gradient.new()
	gradient.add_point(0.0, Color(0.9, 0.95, 1.0, 0.9))  # 剑气前端更亮、更不透明
	gradient.add_point(0.5, Color(0.4, 0.7, 1.0, 0.7))   # 中间部分
	gradient.add_point(1.0, Color(0.2, 0.5, 1.0, 0.0))   # 尾部渐渐消失
	
	var gradient_texture = GradientTexture2D.new()
	gradient_texture.gradient = gradient
	gradient_texture.width = wave_width
	gradient_texture.height = wave_height
	gradient_texture.fill = GradientTexture2D.FILL_LINEAR
	gradient_texture.fill_from = Vector2(0.5, 0.5)
	gradient_texture.fill_to = Vector2(1 if point_right else 0, 0.5)
	
	# 创建精灵，使用渐变纹理
	var sprite = Sprite2D.new()
	sprite.name = "SwordWaveSprite"
	sprite.texture = gradient_texture
	# 调整精灵的形状，使其更细长
	sprite.scale = Vector2(1.5, 0.6)
	add_child(sprite)
	
	# 添加拖尾效果
	var trail = Line2D.new()
	trail.name = "SwordTrail"
	trail.width = 10.0  # 更窄的拖尾
	trail.default_color = Color(0.3, 0.7, 1.0, 0.4)
	trail.texture_mode = Line2D.LINE_TEXTURE_TILE
	trail.joint_mode = Line2D.LINE_JOINT_ROUND
	trail.begin_cap_mode = Line2D.LINE_CAP_ROUND
	trail.end_cap_mode = Line2D.LINE_CAP_ROUND
	trail.z_index = -1  # 确保在主体后面
	add_child(trail)
	
	# 添加发光效果
	var light = PointLight2D.new()
	# 创建一个光照纹理
	var light_texture = GradientTexture2D.new()
	var light_gradient = Gradient.new()
	light_gradient.add_point(0, Color(1, 1, 1, 1))
	light_gradient.add_point(1, Color(0.3, 0.7, 1.0, 0))
	light_texture.gradient = light_gradient
	light_texture.width = 128
	light_texture.height = 128
	light_texture.fill = GradientTexture2D.FILL_RADIAL
	light_texture.fill_from = Vector2(0.5, 0.5)
	light_texture.fill_to = Vector2(1, 0.5)
	
	light.texture = light_texture
	light.color = Color(0.3, 0.7, 1.0, 0.8)
	light.energy = 1.0
	light.texture_scale = 1.0
	light.position = Vector2(wave_width/4 if point_right else -wave_width/4, 0)  # 光源位置在剑气前端
	add_child(light)
	
	# 创建主要粒子效果 - 剑气内的闪烁微粒
	var core_particles = CPUParticles2D.new()
	core_particles.name = "CoreParticles"
	core_particles.position = Vector2(0, 0)
	core_particles.amount = 40  # 增加粒子数量
	core_particles.lifetime = 0.3
	core_particles.local_coords = true
	core_particles.explosiveness = 0.0
	core_particles.randomness = 0.5
	core_particles.direction = Vector2(1 if point_right else -1, 0)
	core_particles.spread = 15  # 减小扩散角度，更集中
	core_particles.gravity = Vector2.ZERO
	core_particles.initial_velocity_min = 20  # 增加速度
	core_particles.initial_velocity_max = 70
	core_particles.scale_amount_min = 1.0
	core_particles.scale_amount_max = 2.5
	core_particles.color = Color(0.9, 0.95, 1.0, 0.8)
	add_child(core_particles)
	
	# 创建边缘粒子效果 - 剑气边缘的飘散微粒
	var edge_particles = CPUParticles2D.new()
	edge_particles.name = "EdgeParticles" 
	edge_particles.position = Vector2(10 if point_right else -10, 0)
	edge_particles.amount = 20  # 增加粒子数量
	edge_particles.lifetime = 0.4
	edge_particles.local_coords = false
	edge_particles.explosiveness = 0.05
	edge_particles.randomness = 0.5
	edge_particles.emission_shape = CPUParticles2D.EMISSION_SHAPE_RECTANGLE
	edge_particles.emission_rect_extents = Vector2(wave_width/3, wave_height/3)  # 更小的发射区域
	edge_particles.direction = Vector2(0, 1)
	edge_particles.spread = 40  # 减小扩散角度
	edge_particles.gravity = Vector2(0, -20)  # 轻微向上的引力
	edge_particles.initial_velocity_min = 15
	edge_particles.initial_velocity_max = 40
	edge_particles.scale_amount_min = 0.5
	edge_particles.scale_amount_max = 1.5
	edge_particles.color = Color(0.4, 0.7, 1.0, 0.5)
	
	# 添加粒子大小变化曲线
	edge_particles.scale_amount_curve = Curve.new()
	edge_particles.scale_amount_curve.add_point(Vector2(0, 1.0))
	edge_particles.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	add_child(edge_particles)
	
	# 创建类似刀光的刻痕效果
	var slash_lines = Node2D.new()
	slash_lines.name = "SlashLines"
	add_child(slash_lines)
	
	# 添加几条锋利的线条，模拟刀光刻痕
	for i in range(5):  # 增加线条数量
		var slash = Line2D.new()
		slash.default_color = Color(0.9, 0.95, 1.0, 0.8 - i * 0.15)
		slash.width = 1.5 - i * 0.2  # 稍微加粗线条
		
		# 线条的点，根据方向调整
		var line_points = []
		var offset = i * 3
		if point_right:
			line_points.append(Vector2(-wave_width/2 + offset, -wave_height/2 + i * 2))
			line_points.append(Vector2(wave_width/2 - offset/2, -i))  # 调整中间点稍微偏上
			line_points.append(Vector2(-wave_width/2 + offset, wave_height/2 - i * 2))
		else:
			line_points.append(Vector2(wave_width/2 - offset, -wave_height/2 + i * 2))
			line_points.append(Vector2(-wave_width/2 + offset/2, -i))  # 调整中间点稍微偏上
			line_points.append(Vector2(wave_width/2 - offset, wave_height/2 - i * 2))
		
		slash.points = line_points
		slash_lines.add_child(slash)
	
	# 添加动画效果 - 脉动和闪烁
	var tween = create_tween()
	tween.tween_property(sprite, "modulate", Color(1.5, 1.5, 1.5, 1.0), 0.1)  # 更亮的闪烁
	tween.tween_property(sprite, "modulate", Color(1.0, 1.0, 1.0, 0.9), 0.1)
	tween.set_loops()

func create_hit_effect(hit_position):
	# 创建击中效果
	var hit_effect = CPUParticles2D.new()
	hit_effect.global_position = hit_position
	hit_effect.amount = 25
	hit_effect.lifetime = 0.4
	hit_effect.explosiveness = 0.9
	hit_effect.direction = Vector2(0, -1)
	hit_effect.spread = 180
	hit_effect.gravity = Vector2(0, 50)
	hit_effect.initial_velocity_min = 100
	hit_effect.initial_velocity_max = 200
	hit_effect.scale_amount_min = 2.0
	hit_effect.scale_amount_max = 4.0
	hit_effect.color = Color(0.3, 0.7, 1.0, 0.8)
	
	# 添加粒子大小和颜色变化
	hit_effect.scale_amount_curve = Curve.new()
	hit_effect.scale_amount_curve.add_point(Vector2(0, 1.0))
	hit_effect.scale_amount_curve.add_point(Vector2(0.7, 0.7))
	hit_effect.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	hit_effect.color_ramp = Gradient.new()
	hit_effect.color_ramp.add_point(0.0, Color(0.9, 0.95, 1.0, 0.9))
	hit_effect.color_ramp.add_point(0.5, Color(0.4, 0.7, 1.0, 0.7))
	hit_effect.color_ramp.add_point(1.0, Color(0.3, 0.5, 0.8, 0.0))
	
	hit_effect.emitting = true
	hit_effect.one_shot = true
	hit_effect.add_to_group("sword_wave_hit")  # 添加到组以便后续清理
	get_parent().add_child(hit_effect)
	
	# 添加冲击波圆形效果
	var ring = Line2D.new()
	ring.global_position = hit_position
	ring.width = 2.0
	ring.default_color = Color(0.4, 0.7, 1.0, 0.7)
	ring.add_to_group("sword_wave_hit")  # 添加到组以便后续清理
	
	# 创建圆形点
	var circle_points = []
	var radius = 10.0
	var segments = 12
	for i in range(segments + 1):
		var angle = i * 2 * PI / segments
		var point = Vector2(cos(angle) * radius, sin(angle) * radius)
		circle_points.append(point)
	
	ring.points = circle_points
	get_parent().add_child(ring)
	
	# 为冲击波创建膨胀动画
	var tween = create_tween()
	tween.tween_property(ring, "width", 1.0, 0.3)
	tween.parallel().tween_property(ring, "scale", Vector2(3, 3), 0.3)
	tween.parallel().tween_property(ring, "modulate", Color(0.4, 0.7, 1.0, 0.0), 0.3)
	
	# 自动清理粒子
	await get_tree().create_timer(hit_effect.lifetime + 0.1).timeout
	if is_instance_valid(hit_effect):
		hit_effect.queue_free()
	
	# 自动清理冲击波
	await tween.finished
	if is_instance_valid(ring):
		ring.queue_free()

func create_disappear_effect():
	# 创建更多样化的消失效果
	var particles = CPUParticles2D.new()
	particles.global_position = global_position
	particles.amount = 40
	particles.lifetime = 0.6
	particles.explosiveness = 0.8
	particles.direction = Vector2(direction.x, 0)  # 保持剑气原方向
	particles.spread = 30
	particles.gravity = Vector2(0, 10)
	particles.initial_velocity_min = 50
	particles.initial_velocity_max = 150
	particles.scale_amount_min = 1.0
	particles.scale_amount_max = 3.0
	
	# 添加粒子大小和颜色变化
	particles.scale_amount_curve = Curve.new()
	particles.scale_amount_curve.add_point(Vector2(0, 1.0))
	particles.scale_amount_curve.add_point(Vector2(0.7, 0.7))
	particles.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	particles.color_ramp = Gradient.new()
	particles.color_ramp.add_point(0.0, Color(0.9, 0.95, 1.0, 0.8))
	particles.color_ramp.add_point(0.5, Color(0.4, 0.7, 1.0, 0.5))
	particles.color_ramp.add_point(1.0, Color(0.2, 0.5, 0.9, 0.0))
	
	particles.emitting = true
	particles.one_shot = true
	particles.add_to_group("sword_wave_vanish")  # 添加到组以便后续清理
	get_parent().add_child(particles)
	
	# 添加消散线效果
	var vanish_lines = Node2D.new()
	vanish_lines.global_position = global_position
	vanish_lines.add_to_group("sword_wave_vanish")  # 添加到组以便后续清理
	get_parent().add_child(vanish_lines)
	
	# 添加几条消散线
	for i in range(5):
		var line = Line2D.new()
		line.default_color = Color(0.4, 0.7, 1.0, 0.7)
		line.width = 2.0
		
		# 生成随机角度的线
		var angle = randf() * 2 * PI
		var length = randf_range(20, 40)
		var points = [Vector2.ZERO, Vector2(cos(angle) * length, sin(angle) * length)]
		line.points = points
		
		vanish_lines.add_child(line)
		
		# 添加线条淡出动画
		var tween = create_tween()
		tween.tween_property(line, "modulate", Color(0.4, 0.7, 1.0, 0.0), 0.4)
		tween.parallel().tween_property(line, "width", 0.5, 0.4)
	
	# 自动清理
	await get_tree().create_timer(particles.lifetime + 0.2).timeout
	if is_instance_valid(particles):
		particles.queue_free()
	if is_instance_valid(vanish_lines):
		vanish_lines.queue_free()

func play_sound_effect():
	# 播放剑气效果音 - 使用更具切割感的声音
	var audio_player = AudioStreamPlayer.new()
	
	# 创建一个更加锐利的音效
	var sound = AudioStreamGenerator.new()
	sound.mix_rate = 44100
	sound.buffer_length = 0.2  # 稍微长一点的声音
	
	audio_player.stream = sound
	audio_player.volume_db = -8
	audio_player.pitch_scale = randf_range(1.2, 1.4)  # 更高音调
	add_child(audio_player)
	audio_player.play()
	
	# 添加第二个音轨，增强切割感
	var audio_player2 = AudioStreamPlayer.new()
	var sound2 = AudioStreamGenerator.new()
	sound2.mix_rate = 44100
	sound2.buffer_length = 0.1
	
	audio_player2.stream = sound2
	audio_player2.volume_db = -15
	audio_player2.pitch_scale = randf_range(1.8, 2.0)  # 更高音调
	add_child(audio_player2)
	audio_player2.play()
	
	# 自动清理
	await get_tree().create_timer(0.5).timeout  # 固定等待时间
	audio_player.queue_free()
	audio_player2.queue_free()

func _exit_tree():
	# 确保在节点移除时清理所有可能在场景中留下的效果
	print("剑气波被清理，确保移除所有视觉效果")
	
	# 获取所有由本节点创建的特效节点
	var hit_effects = get_tree().get_nodes_in_group("sword_wave_hit")
	for effect in hit_effects:
		if is_instance_valid(effect):
			effect.queue_free()
	
	# 查看是否有消散线留在场景中
	var vanish_lines = get_tree().get_nodes_in_group("sword_wave_vanish")
	for line in vanish_lines:
		if is_instance_valid(line):
			line.queue_free()
